import React, { useContext, useEffect, useMemo, useRef, useState } from 'react';
import { Dimensions, FlatList, StyleSheet, TouchableOpacity } from 'react-native';
import { useReactive } from 'ahooks';
import HomeRequest from '../../../../request/homeRequest.ts';
import { useDispatch, useSelector } from 'react-redux';
import { AppDispatch, RootState } from '../../../../redux/store.ts';
import Tools from '../../../../utils/Tools.ts';
import { Text, View } from 'native-base';
import { CommonStyle } from '../../../../common/commonStyle.ts';
import { NativeScrollEvent } from 'react-native/Libraries/Components/ScrollView/ScrollView';
import { NativeSyntheticEvent } from 'react-native/Libraries/Types/CoreEventTypes';
import LoadingIndicator from '../../../../component/LoadingIndicator.tsx';
import to from '../../../../utils/to.ts';
import Empty from '../../../../component/Empty.tsx';
import { updateShoppingCartHours } from '../../../../redux/reducers/app.ts';
import ProductItem from '../../component/ProductItem.tsx';
import { MerchantProductContext } from '../index.tsx';
import { Loading } from '../../../../component/LoadingOverlay.tsx';

interface IProductIndexScreenProps {
  scrollEnabled: boolean;
  headerHeight: number;
  merchantId: number;
  onProdLoadSuccCB: (result: boolean) => void;
}
interface IState {
  height: number;
  categories: IObtainProductCategoriesRes[];
  product: IObtainProductListRes[];
  productLoading: boolean;
}

const windowHeight = Dimensions.get('window').height;
const windowWidth = Dimensions.get('window').width;
const ProductIndexScreen: React.FC<IProductIndexScreenProps> = (props) => {
  const state = useReactive<IState>({ height: 0, categories: [], product: [], productLoading: true });
  const beeperId = useSelector((state: RootState) => state.beeperId);
  const shoppingCart = useSelector((state: RootState) => state.shoppingCart);
  const btnInformation = useSelector((state: RootState) => state.btnInformation);
  const beeperParams = useSelector((state: RootState) => state.beeperParams);
  const dispatch = useDispatch<AppDispatch>();
  const [selectedCategory, setSelectedCategory] = useState<number>(1);
  const categoryHeights = useRef<number[]>([]);
  const [scrolling, setScrolling] = useState(false);
  const rightListRef = useRef<FlatList>(null);
  const { collect } = useContext(MerchantProductContext)!;

  useEffect(() => {
    if (!collect) fetchObtainProductCategories();
  }, []);

  useEffect(() => {
    Loading.show();
    if (collect) {
      state.categories = [];
      state.product = [];
      const params = { businessId: props.merchantId, btnId: btnInformation!.id, beeperId, btnType: btnInformation!.btnType, classifyIds: btnInformation!.classifyIds, queryType: beeperParams.queryType, pageNo: 1, pageSize: 1000, collect: 1 };
      HomeRequest.ObtainCollectedProductList(params)
        .then((res) => {
          state.product = [{ businessClassifyId: 0, businessClassifyName: '', list: res.data.list }];
          Loading.hide();
        })
        .catch(() => Loading.hide());
    } else {
      fetchObtainProductCategories();
    }
  }, [collect]);

  useEffect(() => {
    if (props.headerHeight) state.height = windowHeight - props.headerHeight;
  }, [props.headerHeight]);

  // 获得商户分类列表
  const fetchObtainProductCategories = () => {
    const params = { businessId: props.merchantId, type: 1, btnId: btnInformation!.id, beeperId, btnType: btnInformation!.btnType, classifyIds: btnInformation!.classifyIds, queryType: beeperParams.queryType };
    HomeRequest.ObtainProductCategories(params).then((res) => {
      if (res.data && res.data.length > 0) {
        state.categories = res.data.map((item) => {
          return { ...item, name: Tools.extractChineseTextFromHtml(item.name).toString() };
        });
        setSelectedCategory(res.data[0].id);
      } else {
        state.categories = [];
      }
      fetchObtainProductList();
    });
  };

  // 获得商户产品列表
  const fetchObtainProductList = async () => {
    const params = { businessId: props.merchantId, type: 1, btnId: btnInformation!.id, beeperId, btnType: btnInformation!.btnType, classifyIds: btnInformation!.classifyIds, queryType: beeperParams.queryType, businessClassifyIds: state.categories.map((item) => item.id).toString() };
    const [err, res] = await to(HomeRequest.ObtainProductList(params));
    if (err) {
      state.productLoading = false;
      props.onProdLoadSuccCB(false);
      return;
    }
    if (state.categories.length > 0) {
      state.product = res.data as IObtainProductListRes[];
    } else {
      state.product = [{ businessClassifyId: 0, businessClassifyName: '', list: res.data as IProductInformation[] }];
    }
    // 更新购物车中关于售卖时间的数据
    dispatch(updateShoppingCartHours(Tools.flatProductData(state.product)));
    props.onProdLoadSuccCB(true);
    state.productLoading = false;
    Loading.hide();
  };

  // 点击左侧分类后，设置选中分类并滚动右侧 FlatList 到对应位置
  const handleCategoryPress = (categoryId: number) => {
    setSelectedCategory(categoryId);
    setScrolling(true);
    const index = state.categories.findIndex((item) => item.id === categoryId);
    let offset = 0;
    for (let i = 0; i < index; i++) {
      offset += categoryHeights.current[i] || 0;
    }
    rightListRef.current?.scrollToOffset({ offset, animated: true });
    setTimeout(() => setScrolling(false), 500);
  };

  // 右侧滚动事件监听
  const handleRightListScroll = (event: NativeSyntheticEvent<NativeScrollEvent>) => {
    if (scrolling) return;
    if (state.categories.length < 1) return;
    const offsetY = event.nativeEvent.contentOffset.y;
    let cumulativeHeight = 0;
    for (let i = 0; i < categoryHeights.current.length; i++) {
      cumulativeHeight += categoryHeights.current[i] || 0;
      if (offsetY < cumulativeHeight) {
        const index = state.categories.find((item, index) => index === i)!.id;
        setSelectedCategory(index);
        break;
      }
    }
  };

  // 渲染左侧分类
  const renderCategoryItem = ({ item }: { item: IObtainProductCategoriesRes }) => (
    <TouchableOpacity style={[styles.categoryItem, item.id === selectedCategory && styles.categoryItemSelected]} onPress={() => handleCategoryPress(item.id)}>
      <Text numberOfLines={2} style={item.id === selectedCategory ? styles.selectedText : styles.normalText}>
        {item.name}
      </Text>
    </TouchableOpacity>
  );

  // 渲染右侧商品列表项
  const renderProductItem = ({ item, index }: { item: IObtainProductListRes; index: number }) => {
    return (
      <View
        key={index}
        onLayout={(e) => {
          categoryHeights.current[index] = e.nativeEvent.layout.height - 30;
        }}
      >
        {state.categories.length > 0 && (
          <Text fontSize={12} color={CommonStyle.normalGrey} style={{ marginBottom: 12 }}>
            {state.categories.find((_item) => _item.id === item.businessClassifyId)?.name}
          </Text>
        )}
        {item.list.map((listItem, _index) => {
          return <ProductItem item={listItem} key={_index} />;
        })}
      </View>
    );
  };

  return (
    <View style={[styles.container, { height: state.height + 20 }]}>
      {/* 左侧分类列表 */}
      {state.categories.length > 1 && <FlatList data={state.categories} renderItem={renderCategoryItem} nestedScrollEnabled={props.scrollEnabled} scrollEnabled={props.scrollEnabled} keyExtractor={(item) => item.id.toString()} style={styles.leftList} showsVerticalScrollIndicator={false} />}

      {/* 右侧商品列表 */}
      <FlatList
        data={state.product}
        renderItem={renderProductItem}
        extraData={shoppingCart.length}
        keyExtractor={(item, index) => index.toString()}
        onScroll={handleRightListScroll}
        ref={rightListRef}
        initialNumToRender={5}
        maxToRenderPerBatch={5}
        nestedScrollEnabled={props.scrollEnabled}
        scrollEnabled={props.scrollEnabled}
        style={[styles.rightList, { width: state.categories.length > 1 ? windowWidth - 80 : windowWidth }]}
        ListEmptyComponent={!state.productLoading ? <Empty text={'暂无数据'} /> : null}
        ListFooterComponent={
          state.productLoading ? (
            <View pt={40}>
              <LoadingIndicator text={'加载中'} />
            </View>
          ) : null
        }
      />
    </View>
  );
};
const styles = StyleSheet.create({
  container: { flexDirection: 'row', width: '100%' },
  leftList: { backgroundColor: '#f8f8f8' },
  categoryItem: { width: 80, height: 80, padding: 10, alignItems: 'center', justifyContent: 'center' },
  categoryItemSelected: { backgroundColor: 'white', borderRadius: 0 },
  selectedText: { color: '#ff5a00', fontWeight: 'bold', fontSize: 12 },
  normalText: { color: '#333', fontSize: 12 },
  rightList: { paddingHorizontal: 12 },
  categoryHeader: { paddingVertical: 8, backgroundColor: '#ddd' },
  categoryHeaderText: { fontWeight: 'bold', color: '#333' },
});

export default ProductIndexScreen;
